#include "../include/retrievejson.h"
namespace Json {
	RetrieveJson::RetrieveJson(void)
	{
	}

	RetrieveJson::~RetrieveJson(void)
	{
	}

	string RetrieveJson::retrieveJson(const string& sn)
	{
		string *json=new string();
		HINTERNET hSession=NULL,
			hConnection=NULL,
			hRequest=NULL;
		bool ok;
		DWORD dwSize = 0;
		DWORD dwDownloaded = 0;
		LPSTR pszOutBuffer=NULL;

		string s("tpsp/tpsp.php?code=");
		s.append(sn);

		hSession=WinHttpOpen(0,
			WINHTTP_ACCESS_TYPE_NO_PROXY,
			WINHTTP_NO_PROXY_NAME,
			WINHTTP_NO_PROXY_BYPASS,0);
		if(hSession)
		{
			hConnection=WinHttpConnect(hSession,
				L"nmi.cuc.edu.cn",
				INTERNET_DEFAULT_HTTP_PORT,0);
		}
		if(hConnection)
		{
			hRequest=WinHttpOpenRequest(hConnection,
				NULL,
				stringToLPCWSTR(s),
				NULL,
				WINHTTP_NO_REFERER,
				WINHTTP_DEFAULT_ACCEPT_TYPES,0);					
		}
		if (hRequest) 
			ok=WinHttpSendRequest(hRequest, 
			WINHTTP_NO_ADDITIONAL_HEADERS,
			0, WINHTTP_NO_REQUEST_DATA, 0, 
			0, 0);
		if (ok)
			ok = WinHttpReceiveResponse( hRequest, NULL);

		// Keep checking for data until there is nothing left.
		if (ok)
		{
			do 
			{
				// Check for available data.
				dwSize = 0;
				if (!WinHttpQueryDataAvailable( hRequest, &dwSize)) 
				{
					printf( "Error %u in WinHttpQueryDataAvailable.\n",
						GetLastError());
					break;
				}

				// No more available data.
				if (!dwSize)
					break;

				// Allocate space for the buffer.
				pszOutBuffer = new char[dwSize+1];
				if (!pszOutBuffer)
				{
					printf("Out of memory\n");
					break;
				}

				// Read the Data.
				ZeroMemory(pszOutBuffer, dwSize+1);

				if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer, 
					dwSize, &dwDownloaded))
				{                                  
					printf( "Error %u in WinHttpReadData.\n", GetLastError());
				}
				else
				{
					json->append(pszOutBuffer);
				}

				// Free the memory allocated to the buffer.
				delete [] pszOutBuffer;

				// This condition should never be reached since WinHttpQueryDataAvailable
				// reported that there are bits to read.
				if (!dwDownloaded)
					break;

			} while (dwSize > 0);
		}
		WinHttpCloseHandle(hRequest);
		WinHttpCloseHandle(hConnection);
		WinHttpCloseHandle(hSession);

		return *json;
	}

	LPCWSTR stringToLPCWSTR(const string& s)
	{
		int len;
		int slength = (int)s.length() + 1;
		len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
		wchar_t* buf = new wchar_t[len];
		MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
		return buf;
	}
}